package pers.jason.wppm.security.authentication;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import com.fasterxml.jackson.databind.ObjectMapper;

import pers.jason.wppm.security.core.properties.LoginType;
import pers.jason.wppm.security.core.properties.SecurityProperties;
import pers.jason.wppm.security.core.validate.code.support.SimpleResponse;

/**
 * 
 * @author Jason
 * @Date 2018-10-29 10:37
 *
 */
@Component
public class DefaultAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler  {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private ObjectMapper objectMapper;
	
	@Autowired
	private SecurityProperties securityProperties;
	
	private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
	
	
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		// TODO Auto-generated method stub
		//super.onAuthenticationSuccess(request, response, authentication);
		logger.info("登陆成功");
		sessionStrategy.removeAttribute(new ServletWebRequest(request), "LOGIN_ERROR_MSG");
		String loginType = securityProperties.getBrowser().getLoginResponseType();
		if(LoginType.LOGIN_RESPONSE_TYPE_JSON.equals(StringUtils.upperCase(loginType))) {
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write(objectMapper.writeValueAsString(SimpleResponse.createSuccessResponse("登陆成功", authentication)));
		} else {
			super.onAuthenticationSuccess(request, response, authentication);
		}
	}



}
